/*
 * Copyright (C) 2013. Young,Fey <fey.young@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.youngfey.util

import groovy.transform.*

/**
 * 配置文件工具类
 * @author Young , Fey <fey.young@gmail.com>
 * @version 0.1.d
 * Created at 2013-04-24 20:38
 */
@TupleConstructor
class Configuration {
    static Configuration getInstanceHere(String filename) {
        new Configuration(filename, System.getProperty('user.dir'))
    }

    //注意，指定目录下不恰当的文件将导致异常或空配置对象
    static List<Configuration> getInstances(String path, Object nameFilter) {
        def list = []
        new File(path).eachFileMatch nameFilter, {
            list << new Configuration(it.name, path)
        }
        list
    }

    String get(String key) {
        if(!prop) init()
        prop.getProperty(key)
    }

    Integer getInteger(String key) {
        final String value = get(key)
        value?.integer ? Integer.valueOf(value) : null
    }

    void set(String key, value) {
        if(!prop) init()
        if(value == null) prop.remove(key)
        else prop.setProperty(key, value?.toString())
    }

    void save() {
        prop?.store(new FileOutputStream(file), 'Updated by configure-loader')
    }

    private void init() {
        def dir = new File(path)
        dir.mkdirs()
        assert dir.directory, "$dir must be a folder"

        file = new File(dir, filename)
        file.createNewFile()
        assert file.file, "$file.name must be an existed file under $dir"

        prop = new Properties()
        prop.load(new FileInputStream(file))
    }

    final String filename, path = System.getProperty('user.home')
    private File file
    private Properties prop
}
